package com.example.admin_beautiful.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 静态资源处理
 */
@Configuration
@Slf4j
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Value("${localhost.path}")
    private String imagePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        Path path = Paths.get(imagePath);
        if(!(Files.exists(path) && Files.isDirectory(path))){
            try {
                Files.createDirectories(path);
                log.info("目录已创建成功："+imagePath);
            } catch (IOException e) {
                log.error("目录创建失败："+imagePath);
                throw new RuntimeException(e);
            }
        }
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + imagePath+"/images/");
    }

}
